package edu.upc.dew.service;

import edu.upc.dew.dao.AccountDao;
import edu.upc.dew.entity.Account;
import edu.upc.dew.service.exception.BusinessException;
import edu.upc.dew.util.KeycodeManager;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 *
 * @author gian
 *
 */
@Service
public class AccountService {

    private static final Logger log = LoggerFactory.getLogger(AccountService.class);

    PasswordEncoder encoder = new Md5PasswordEncoder();

    @Autowired
    private AccountDao accountDao;


    /**
     * Permite autenticar una cuenta. Retorna un keycode y la información de la
     * cuenta misma.
     *
     * @param email
     * @param password
     * @return
     */
    public Map<String,Object> authenticate(String email,String password) throws BusinessException {
        log.info("Autenticando cliente: email="+email+", password=AJA!");
        Map<String,Object> result = new HashMap<String,Object>();

        if (email.isEmpty() || password.isEmpty() ) {
            throw new BusinessException("El correo o contraseña no pueden ser null");
        }

        Account account = accountDao.getAccount(email);

        if (account != null &&
            !account.getEmail().isEmpty() &&
            !account.getPassword().isEmpty()) {

            if (encoder.isPasswordValid(account.getPassword(), password, null)) {
                log.info("Cuenta autenticada correctamente");
                result.put("keycode",KeycodeManager.generateKeyCode(account.getId().toString()));
                result.put("account",account);
                return result;
            } else {
                log.info("Clave de cuenta incorrecta");
                throw new BusinessException("Clave de cuenta incorrecta");
            }
        } else {
            log.info("No se encontró la cuenta o faltan datos");
            throw new BusinessException("No se encuentra la cuenta o faltan datos");
        }
    }

    public boolean addUser(Account account) {
        if (account!= null && account.getPassword() != null) {
            account.setPassword(encoder.encodePassword(account.getPassword(),null));
        }
        accountDao.addUser(account);
        return true;
    }
}
